import React, { useState, useEffect } from "react";
import ReactEcharts from "echarts-for-react";
import { Card, Button } from "antd";

const Bar = () => {
  const [sales, setSales] = useState([]);
  const [stores, setStores] = useState([]);

  useEffect(() => {
    const fetchData = () => {
      const res = {
        status: 0,
        data: {
          sales: [5, 20, 36, 10, 10, 20],
          stores: [2, 4, 10, 6, 6, 8],
        },
      };

      if (res.status === 0) {
        const { sales, stores } = res.data;
        setSales(sales);
        setStores(stores);
      }
    };

    setTimeout(fetchData, 100);
  }, []);

  const getOption = (sales, stores) => ({
    title: {
      text: "柱形图示例",
      link: "http://www.baidu.com",
      textStyle: {
        color: "red",
      },
    },
    tooltip: {},
    legend: {
      data: ["销量", "库存"],
    },
    xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
    },
    yAxis: {},
    series: [
      {
        name: "销量",
        type: "bar",
        data: sales,
      },
      {
        name: "库存",
        type: "bar",
        data: stores,
      },
    ],
  });

  const update = () => {
    setSales(sales.map((sale) => sale + 1));
    setStores(stores.map((store) => store - 1));
  };

  return (
    <div>
      <Card
        title={
          <Button type="primary" onClick={update}>
            更新数据
          </Button>
        }
      >
        <ReactEcharts
          option={getOption(sales, stores)}
          style={{ height: "400px", width: "100%" }} // 调整高度和宽度
        />
      </Card>
    </div>
  );
};

export default Bar;
